
package juc2.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 超时获取锁 Demo
 */
public class ReentrantLockTryLockDemo {
    private static final Lock lockA = new ReentrantLock();
    private static final Lock lockB = new ReentrantLock();

    // 尝试获取锁A和锁B，超时则放弃
    public static void transfer() throws InterruptedException {
        // 尝试在1秒内获取锁A
        if (lockA.tryLock(1, TimeUnit.SECONDS)) {
            try {
                //睡眠5秒，模拟转账操作
                TimeUnit.SECONDS.sleep(5);
                // 尝试在1秒内获取锁B
                if (lockB.tryLock(1, TimeUnit.SECONDS)) {
                    try {
                        System.out.println(Thread.currentThread().getName() + "成功获取两把锁，执行转账逻辑");
                    } finally {
                        lockB.unlock();
                    }
                } else {
                    System.out.println(Thread.currentThread().getName() + "获取锁B超时，放弃操作");
                }
            } finally {
                lockA.unlock();
            }
        } else {
            System.out.println(Thread.currentThread().getName() + "获取锁A超时，放弃操作");
        }
    }

    public static void main(String[] args) {
        // 启动两个线程，模拟两个线程同时执行转账操作
        new Thread(() -> {
            try {
                transfer();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "线程A").start();

        new Thread(() -> {
            try {
                transfer();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "线程B").start();
    }
}
